//
//  SportHistoryRecordViewController.m
//  CoolMove
//
//  Created by CA on 15/10/26.
//  Copyright © 2015年 CA. All rights reserved.
//

#import "SportHistoryRecordViewController.h"
#import "PNChart.h"
#import "ChartItem.h"
#import "NSDate+FormateString.h"
#import <UICountingLabel/UICountingLabel.h>
#import "NSDate+CM_DateTools.h"
#import "WeekHandleItem.h"
#import "SportReportViewController.h"
#import <DateTools/NSDate+DateTools.h>

static const NSInteger kCountOfBars = 10;
static const CGFloat kCountingLabelDuration = 1.0f;
static const CGFloat kMaxSportDuration = 10.0f;
static const CGFloat kPerBarMargin = 3.0f;

static NSString * const kSportReportSegue = @"SportReportSegue";

@interface SportHistoryRecordViewController ()
@property (weak, nonatomic) IBOutlet UIScrollView *chartScrollView;
@property (nonatomic, strong) PNBarChart *barChart;
@property (nonatomic, strong) NSArray *barItems;
@property (nonatomic, strong) RLMResults *sportRecords;

@property (weak, nonatomic) IBOutlet UICountingLabel *averageCaloriesLabel;
@property (weak, nonatomic) IBOutlet UICountingLabel *averageSwingCountLabel;
@property (weak, nonatomic) IBOutlet UICountingLabel *averageSportDurationLabel;
@property (weak, nonatomic) IBOutlet UICountingLabel *amountCaloriesLabel;
@property (weak, nonatomic) IBOutlet UICountingLabel *amountSwingCountLabel;
@property (weak, nonatomic) IBOutlet UICountingLabel *maxSpeedLabel;
@property (weak, nonatomic) IBOutlet UILabel *weekStartEndDateLabel;
@property (weak, nonatomic) UILabel *currentSportDurationLabel;


//国际化
@property (weak, nonatomic) IBOutlet UILabel *averageCalDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalCalDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *maxSpeedDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *averageActiveTimeDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *averageHitTimeDescriptionLabel;//平局击球次数
@property (weak, nonatomic) IBOutlet UILabel *totalHitTimeDescriptionLabel;

@property (assign, nonatomic) CGFloat perBarWidth; //每一条bar的宽度

@end

@implementation SportHistoryRecordViewController
{
    NSUInteger _indexOfLastSelectedBar; // 记住上一次的选中柱状条
    NSUInteger _indexOfLastAnimation;   // 记住最后一次动画的柱状条，用于滑动最后显示
}

#pragma mark - View LifeCycle

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        _perBarWidth = [UIScreen mainScreen].bounds.size.width * 2 / kCountOfBars - kPerBarMargin;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.user = [User getLastUser];
    
    [self configureLocation];
    [self configureCountingLabels];
    [self configureHistoryRecordForShow];
    
    CGFloat barMargin = self.view.bounds.size.width * 2/10 - self.perBarWidth;
    [self.chartScrollView setContentOffset:CGPointMake(([self.weekHandleItems count] - 1) * (barMargin + self.perBarWidth), 0)];
    
    if (self.weekHandleItems.count < 1) {
        self.navigationItem.rightBarButtonItem = nil;
    }
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"sport_icon_blackbackArrow"] style:UIBarButtonItemStylePlain target:self action:@selector(goBack)];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if (self.flag) {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Sport" bundle:nil];
        SportReportViewController *reportController = [storyBoard instantiateViewControllerWithIdentifier:@"SportReportViewController"];
        [self.navigationController pushViewController:reportController animated:YES];
    }
    
    [self configureHistoryRecordForShow];
}

#pragma mark - IBAction

- (IBAction)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Private Method

- (void)goBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)configureLocation{
    
    self.averageCalDescriptionLabel.text = NSLocalizedString(@"Average Calories", nil);
    self.averageHitTimeDescriptionLabel.text =NSLocalizedString(@"Average Shots", nil);
    self.averageActiveTimeDescriptionLabel.text = NSLocalizedString(@"Average Sports Hours", nil);
    self.totalCalDescriptionLabel.text = NSLocalizedString(@"Total Energy Consumption", nil);
    self.totalHitTimeDescriptionLabel.text = NSLocalizedString(@"Total Shots", nil);
    self.maxSpeedDescriptionLabel.text = NSLocalizedString(@"Max. Speed of Swing", nil);
    self.title = NSLocalizedString(@"History", nil);
}

- (void)configureCountingLabelWithWeekHandleItem:(WeekHandleItem *)weekHandleItem
{
    [self.averageCaloriesLabel countFrom:0 to:[weekHandleItem.averageCalories floatValue] withDuration:kCountingLabelDuration];
    [self.averageSwingCountLabel countFrom:0 to:[weekHandleItem.averageSwingCount floatValue]  withDuration:kCountingLabelDuration
     ];
    [self.amountCaloriesLabel countFrom:0 to:[weekHandleItem.amountCalories floatValue]  withDuration:kCountingLabelDuration];
    [self.amountSwingCountLabel countFrom:0 to:[weekHandleItem.amountSwingCount floatValue]  withDuration:kCountingLabelDuration];
    [self.maxSpeedLabel countFrom:0 to:[weekHandleItem.maxSpeed floatValue]  withDuration:kCountingLabelDuration];
    [self.averageSportDurationLabel countFrom:0 to:[weekHandleItem.averageSportDuration floatValue]  withDuration:kCountingLabelDuration];
    self.weekStartEndDateLabel.text = weekHandleItem.startEndDateStr;
    
}

#pragma mark <柱状图显示> 

- (void)configureHistoryRecordForShow
{
    NSDate *endDate   = [NSDate date];
    NSDate *startDate = [NSDate formateString:@"2014-01-01 00:00:00"];
    long long endDateTimeStamp = [endDate unixTimeStamp];
    long long startDateTimeStamp = [startDate unixTimeStamp];
    
    self.sportRecords = [self.user.sportRecordItems objectsWhere:@"dateTimeStamp > %lld AND dateTimeStamp < %lld", startDateTimeStamp,endDateTimeStamp];
    self.sportRecords = [self.sportRecords objectsWhere:@"shouldShield == NO"];
    self.sportRecords = [self.sportRecords sortedResultsUsingProperty:@"dateTimeStamp" ascending:YES];
    self.weekHandleItems = [self weekHandleItemsBySportRecordList:(NSArray *)self.sportRecords];
    
    [self.view layoutIfNeeded];
    self.chartScrollView.frame = CGRectMake(0, self.chartScrollView.frame.origin.y, [UIScreen mainScreen].bounds.size.width, self.chartScrollView.bounds.size.height);
    [self configureBarChartWithWeekHandleItems:self.weekHandleItems];
    
    WeekHandleItem *lastWeekHandleItem = [self.weekHandleItems lastObject];
    [self configureCountingLabelWithWeekHandleItem:[self.weekHandleItems lastObject]];
    [self addSportDurationLabelWithText:[NSString stringWithFormat:@"%@h", lastWeekHandleItem.amountSportDuration] atIndex:[self.weekHandleItems count] - 1];
    
    
}

- (void)configureBarChartWithWeekHandleItems:(NSArray *)chartItems
{
    if (self.barChart) {
        [self.barChart removeFromSuperview];
        _indexOfLastAnimation = 0;
        _indexOfLastSelectedBar = 0;
    }
    
    CGFloat chartBarMargin = self.chartScrollView.bounds.size.width * 2/kCountOfBars - self.perBarWidth;
    
    self.barChart = [[PNBarChart alloc] initWithFrame:CGRectMake(self.chartScrollView.bounds.size.width/2.0f - self.perBarWidth/2.0f - chartBarMargin/2.0f, 5.0f, (self.chartScrollView.bounds.size.width * 2/kCountOfBars) * [chartItems count] , self.chartScrollView.bounds.size.height - 5.0f)];
    self.chartScrollView.contentSize = CGSizeMake((self.chartScrollView.bounds.size.width * 2/kCountOfBars) * [chartItems count] + self.chartScrollView.bounds.size.width - self.perBarWidth - chartBarMargin, self.chartScrollView.bounds.size.height);
    self.barChart.backgroundColor = [UIColor clearColor];
    self.barChart.yLabelFormatter = ^(CGFloat yValue){
        CGFloat yValueParsed = yValue;
        NSString * labelText = [NSString stringWithFormat:@"%1.f",yValueParsed];
        return labelText;
    };
    
    self.barChart.barRadius = 0.0f;
    self.barChart.barWidth = self.perBarWidth;
    self.barChart.labelMarginTop = 1.0f;
    self.barChart.yChartLabelWidth = 0.0f;
    self.barChart.chartMarginTop = 0.0f;
    self.barChart.chartMarginLeft = 0.0f;
    self.barChart.chartMarginRight = 0.0f;
    self.barChart.chartMarginBottom = 0.0f;
    self.barChart.labelTextColor = kUnSelectedColor;
    self.barChart.labelFont = [UIFont systemFontOfSize:10];
    self.barChart.strokeColors = [self colorsForBarChartWithChartItems:chartItems];
    self.barChart.barBackgroundColor = [UIColor colorWithWhite:1.0f alpha:0.1];
    
    self.barChart.yMaxValue = kMaxSportDuration;
    [self.barChart setXLabels:[self numberOfWeekStringWithWeekHandleItems:chartItems]];
    if (chartItems.count != 0) {
        [self.barChart setYValues: [self sportDurationForBarChartYValuesWithWeekHandleItems:chartItems]];
    }
    self.barChart.isShowNumbers = NO;
    
    // Adding gradient
    [self.barChart strokeChart];
    [self.chartScrollView addSubview:self.barChart];
}

- (void)addSportDurationLabelWithText:(NSString *)text
                              atIndex:(NSUInteger)index
{
    if (index >= [self.barChart.bars count]) {
        return;
    }
    
    if (self.currentSportDurationLabel != nil) {
        [self.currentSportDurationLabel removeFromSuperview];
    }
    
    CGFloat barMargin = self.chartScrollView.bounds.size.width * 2/10 - self.perBarWidth;
    CGFloat startX = self.chartScrollView.bounds.size.width/2.0f - self.perBarWidth/2.0f - barMargin;
    CGFloat barXPosition = index * (self.perBarWidth + barMargin) + barMargin;
    CGFloat chartCavanHeight = self.barChart.frame.size.height - self.barChart.chartMarginTop * 2 - kXLabelHeight;
    CGFloat grace = MIN([self.barChart.bars[index] grade], 1.0f);
    
    CGFloat sportDurationHeight = chartCavanHeight * 0.1f;
    UILabel *sportDurationLabel = [[UILabel alloc] initWithFrame:CGRectMake(barXPosition + startX, chartCavanHeight * (1 - grace) - sportDurationHeight, self.perBarWidth, sportDurationHeight)];
    
    sportDurationLabel.backgroundColor = [UIColor clearColor];
    sportDurationLabel.textAlignment = NSTextAlignmentCenter;
    sportDurationLabel.textColor = kUnSelectedColor;
    sportDurationLabel.text = text;
    sportDurationLabel.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:18.0];
    [self.chartScrollView addSubview:sportDurationLabel];
    
    self.currentSportDurationLabel = sportDurationLabel;
    
    sportDurationLabel.alpha = 0.0f;
    [UIView animateWithDuration:kCountingLabelDuration animations:^{
        sportDurationLabel.alpha = 1.0f;
    }];
}

- (NSArray *)sportDurationForBarChartYValuesWithWeekHandleItems:(NSArray *)weekHandleItems
{
    NSMutableArray *sportDurationValues = [@[] mutableCopy];
    for (WeekHandleItem *item in weekHandleItems) {
        // 0.9系数是为了最顶层保留足够的位置显示时间文本栏
        [sportDurationValues addObject:@([item.amountSportDuration floatValue] * 0.9)];
    }
    
    return [sportDurationValues copy];
}

- (NSArray *)colorsForBarChartWithChartItems:(NSArray *)chartItems
{
    NSMutableArray *colors = [@[] mutableCopy];
    for (NSUInteger index = 0; index < [chartItems count]; index++) {
        if (index == 0) {
            [colors addObject:[UIColor colorWithHex:0x1ba189 alpha:0.2]];
        } else {
            [colors addObject:[UIColor colorWithHex:0x1ba189 alpha:0.2]];
        }
    }
    
    return [colors copy];
}

- (NSArray *)weekStartEndDateStringsWithWeekHandleItems:(NSArray *)weekHandleItems
{
    NSMutableArray *weekStartEndDates = [@[] mutableCopy];
    for (WeekHandleItem *item in weekHandleItems) {
        [weekStartEndDates addObject:item.startEndDateStr];
    }
    return [weekStartEndDates copy];
}

//第几周字符串
- (NSArray *)numberOfWeekStringWithWeekHandleItems:(NSArray *)weekHandleItems
{
    NSMutableArray *numberOfWeekStringArray = @[].mutableCopy;
    for (NSInteger i = 0; i < weekHandleItems.count; i++) {
        [numberOfWeekStringArray addObject:[NSString stringWithFormat:NSLocalizedString(@"Week %zd", nil),(index + 1)]];
    }
    return numberOfWeekStringArray;
}

#pragma mark - 周日期数据 -

- (NSArray *)weekHandleItemsBySportRecordList:(NSArray *)sportRecordItems
{
    NSMutableArray *weekItems = [@[] mutableCopy];
    WeekHandleItem *weekHandleItem = [[WeekHandleItem alloc] init];
    for (SportRecordItem *sportRecordItem in sportRecordItems) {
        
        NSString *monday = [[sportRecordItem date] convertMonthDayByWeekDay:WeekDayMonday];
        NSString *sunday = [[sportRecordItem date] convertMonthDayByWeekDay:WeekDaySunday];
        NSString *startEndDateStr = [NSString stringWithFormat:@"%@-%@", monday, sunday];
        
        if ([weekHandleItem.startEndDateStr isEqualToString:startEndDateStr]) {
            [weekHandleItem addSportRecordItem:sportRecordItem];
        } else {
            weekHandleItem = [[WeekHandleItem alloc] init];
            [weekHandleItem addSportRecordItem:sportRecordItem];
        }
        
        if (![weekItems containsObject:weekHandleItem]) {
            //添加挥拍次数为空的周
//            WeekHandleItem *lastWeekItem = [weekItems lastObject];
//            if (lastWeekItem != nil) {
//                NSArray *fillEmptyWeekItems = [self fillEmptyWeekHandleItemWithStartDate:lastWeekItem.computeDate endDate:sportRecordItem.date];
//                if ([fillEmptyWeekItems count] > 0) {
//                    [weekItems addObjectsFromArray:fillEmptyWeekItems];
//                }
//            }
            
            [weekItems addObject:weekHandleItem];
        }
    }
    
    return [weekItems copy];
}

- (NSArray *)fillEmptyWeekHandleItemWithStartDate:(NSDate *)startDate endDate:(NSDate *)endate
{
    NSInteger weekFromDate = [endate weeksFrom:startDate];
    if (weekFromDate > 0) {
        NSMutableArray *fillEmptyWeekHandleItems = [@[] mutableCopy];
        for (NSInteger index = 1; index <= weekFromDate; index++) {
            NSDate *emptyDate = [startDate dateByAddingWeeks:index];
            WeekHandleItem *weekHandleItem = [[WeekHandleItem alloc] initEmptyItemWithDate:emptyDate];
            [fillEmptyWeekHandleItems addObject:weekHandleItem];
        }
        
        return [fillEmptyWeekHandleItems copy];
    }
    
    return nil;
}

- (WeekHandleItem *)nearestWeekHandleItemToIndex:(NSInteger)weekIndex
{
    for (NSInteger index = weekIndex - 1; index > 0; index--) {
        if (index < [self.weekHandleItems count] && index > 0) {
            WeekHandleItem *nearestHandleItem = self.weekHandleItems[index];
            if (nearestHandleItem.hasSportValue) {
                return nearestHandleItem;
            }
        }
    }
    
    return nil;
}


#pragma mark - 配置跳动文本栏 -

- (void)configureCountingLabels
{
    [self configureCountingLabels:@[self.averageCaloriesLabel, self.averageSwingCountLabel, self.amountCaloriesLabel, self.amountSwingCountLabel, self.maxSpeedLabel] withFormat:@"%d"];
    [self configureCountingLabels:@[self.averageSportDurationLabel] withFormat:@"%.1f"];
}

- (void)configureCountingLabels:(NSArray *)countingLabels withFormat:(NSString *)format
{
    for (UICountingLabel *countingLabel in countingLabels) {
        countingLabel.text = @"0";
        countingLabel.format = format;
        countingLabel.method = UILabelCountingMethodEaseInOut;
    }
}

#pragma mark - UIScrollView Delegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{

    CGFloat contentOffset = scrollView.contentOffset.x;
    CGFloat chartBarMargin = self.chartScrollView.bounds.size.width * 2/kCountOfBars - self.perBarWidth;
    NSUInteger indexOfBar = (contentOffset + (self.perBarWidth + chartBarMargin)/2.0f)/(self.perBarWidth + chartBarMargin);
    if (indexOfBar >= [self.barChart.bars count]) {
        return;
    }
    
    PNBar *bar = self.barChart.bars[indexOfBar];
    CGFloat barX = bar.frame.origin.x;
    if (contentOffset - barX == -2) {
        
    }else{
        [UIView animateWithDuration:0.3 animations:^{
            scrollView.contentOffset = CGPointMake(barX-chartBarMargin/2, 0);
        }];
    }

    

    if (_indexOfLastAnimation == _indexOfLastSelectedBar) {
        return;
    }
    NSLog(@"滑动结束");
    
    _indexOfLastAnimation = _indexOfLastSelectedBar;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    NSLog(@"decelerate:%d", decelerate);
    
    CGFloat contentOffset = scrollView.contentOffset.x;
    CGFloat chartBarMargin = self.chartScrollView.bounds.size.width * 2/kCountOfBars - self.perBarWidth;
    NSUInteger indexOfBar = (contentOffset + (self.perBarWidth + chartBarMargin)/2.0f)/(self.perBarWidth + chartBarMargin);
    if (indexOfBar >= [self.barChart.bars count]) {
        return;
    }
    
    PNBar *bar = self.barChart.bars[indexOfBar];
    CGFloat barX = bar.frame.origin.x;
    if (contentOffset - barX == -2) {
        
    }else{
        [UIView animateWithDuration:0.3 animations:^{
            scrollView.contentOffset = CGPointMake(barX-chartBarMargin/2, 0);
        }];
    }
    
    
    if (_indexOfLastAnimation == _indexOfLastSelectedBar) {
        return;
    }
    
    NSLog(@"停止拖拉..%d", decelerate);
    _indexOfLastAnimation = _indexOfLastSelectedBar;
}



- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat contentOffset = scrollView.contentOffset.x;
        NSLog(@"contentOffset:%f", contentOffset);
    
    CGFloat chartBarMargin = self.chartScrollView.bounds.size.width * 2/kCountOfBars - self.perBarWidth;
    NSUInteger indexOfBar = (contentOffset + (self.perBarWidth + chartBarMargin)/2.0f)/(self.perBarWidth + chartBarMargin);
    
    if (indexOfBar >= [self.barChart.bars count]) {
        return;
    }
    
    PNBar *bar = self.barChart.bars[indexOfBar];
    
    bar.barColor = [UIColor colorWithHex:0x1ba189 alpha:0.2];

    if (_indexOfLastSelectedBar != indexOfBar) {
        PNBar *lastBar = self.barChart.bars[_indexOfLastSelectedBar];
        lastBar.barColor = [UIColor colorWithHex:0x1ba189 alpha:0.2];
        _indexOfLastSelectedBar = indexOfBar;
        WeekHandleItem *weekHandleItem = self.weekHandleItems[indexOfBar];
        [self addSportDurationLabelWithText:[NSString stringWithFormat:@"%@h", weekHandleItem.amountSportDuration] atIndex:indexOfBar];
        [self configureCountingLabelWithWeekHandleItem:weekHandleItem];
    }
}

@end
